package com.net.tomcat5.Servlet4;

import org.xml.sax.SAXException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;

/**
 * 通过反射进行
 *
 * @author jiangbang
 * @date 2016/8/25
 */
public class WebApp {
    private static ServletContext context;

    static {
            try {
                //1.获取解析工长
                SAXParserFactory factory = SAXParserFactory.newInstance();
                //2.从解析工厂获取解析器
                SAXParser parser = factory.newSAXParser();
                //3.加载文档 document 注册处理器
                WebHandler web = new WebHandler();
                //4.编写处理器
                parser.parse(new FileInputStream(new File("E:\\git_repo\\demo-git\\src\\main\\java\\com\\net\\tomcat5\\Servlet4\\web.xml")), web);
                context = new ServletContext();
                Map<String, String> mapping = context.getMapping();
//             servlet.put("login", "com.net.tomcat5.Servlet3.LoginServlet");
                for(Entity entity:web.getEntityList()){
                    mapping.put(entity.getName(), entity.getCla());
                }
                Map<String, String> servlet = context.getServlet();
                for(Mapping mapping1:web.getMappingList()){
                    List<String> urlList = mapping1.getUrlPattern();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    public static Servlet getServlet(String url) {
        if (null == url || url.equals("")) {
            return null;
        }
        //根据字符创创建对象
        String name = context.getServlet().get(context.getMapping().get(url));
        try {
            return (Servlet) Class.forName(name).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
